﻿using System;
using System.IO;
using UnityEditor;

public static class EditorUtils
{
    public static void ForeachTexture(Action<TextureImporter, string> func)
    {
        if (func == null) return;

        var assetGUIDs = Selection.assetGUIDs;

        if (assetGUIDs is { Length: > 0 })
        {
            for (var i = 0; i < assetGUIDs.Length; i++)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]);

                if (File.Exists(assetPath)) continue;

                var assetGUIDsInFolder = AssetDatabase.FindAssets("t:Texture", new[] { assetPath });

                foreach (var guid in assetGUIDsInFolder)
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    var asset = AssetImporter.GetAtPath(path);

                    if (asset is not TextureImporter textureAsset) continue;

                    func(textureAsset, path);
                }
            }
        }

        var objects = Selection.objects;

        if (objects is { Length: > 0 })
        {
            foreach (var item in objects)
            {
                var path = AssetDatabase.GetAssetPath(item);
                var asset = AssetImporter.GetAtPath(path);

                if (asset is not TextureImporter textureAsset) continue;

                func(textureAsset, path);
            }
        }
    }

    public static void Foreach(Action<string> func, string filter)
    {
        if (func == null) return;

        var assetGUIDs = Selection.assetGUIDs;
        if (assetGUIDs is { Length: > 0 })
        {
            for (var i = 0; i < assetGUIDs.Length; i++)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]);

                if (File.Exists(assetPath)) continue;

                var assetGUIDsInFolder = AssetDatabase.FindAssets(filter, new[] { assetPath });

                foreach (var guid in assetGUIDsInFolder)
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    // var asset = AssetImporter.GetAtPath(path);

                    func(path);
                }
            }
        }

        var objects = Selection.objects;
        if (objects is { Length: > 0 })
        {
            foreach (var item in objects)
            {
                var path = AssetDatabase.GetAssetPath(item);
                // var asset = AssetImporter.GetAtPath(path);

                func(path);
            }
        }
    }


    // List<EditorBuildSettingsScene> scenes = new List<EditorBuildSettingsScene>();
    //     foreach (string sceneName in sceneNames)
    // {
    //     scenes.Add(new EditorBuildSettingsScene(sceneName, true));
    // }
    //
    // EditorBuildSettings.scenes = scenes.ToArray();
}